
import 'dart:async';
import 'package:flutter/services.dart';

typedef void EventHandler(Map<String, dynamic> event);
typedef void EventHandlerInt(Status event);

enum Status {
  ///蓝牙未连接
  IDLE,
  ///蓝牙连接中
  CONNECTING,
  ///蓝牙已连接
  CONNECTED,
  ///断开蓝牙连接
  DISCONNECT,
  ///蓝牙连接失败
  CONNECT_FAIL,
  ///蓝牙连接超时
  CONNECT_TIMEOUT,
  ///蓝牙已关闭
  BLUETOOTH_OFF,
  ///蓝牙权限未开启
  UNAUTHORIZED,
  ///蓝牙已配对
  PINNED,
}

class Bluetooth {
  static const MethodChannel _channel = const MethodChannel('com.jacky.util/blue');

  static EventHandler? _onDiscoverPeripheral;
  static EventHandlerInt? _onUpdateState;
  static Function(String data)? _onDataCallback;

  ///自动连接蓝牙设备
  ///
  ///[bluetoothName] 蓝牙名称
  static void connect(String bluetoothName, {String? bluetoothAddress,bool showLog = false}){
    assert(bluetoothName.isNotEmpty);
    _channel.invokeMethod("startWithAutoConnect", {'showLog': showLog,'name':bluetoothName,'address':bluetoothAddress});
  }

  static void stop() {
    _channel.invokeMethod("stop");
    _onUpdateState = null;
    _onDiscoverPeripheral = null;
    _onDataCallback = null;
  }

  ///连接设备
  static void connectPeripheral(String bluetoothName) {
    assert(bluetoothName.isNotEmpty);
    _channel.invokeMethod("connectPeripheral",bluetoothName);
  }

  ///重启扫码
  static void reStartScan() {
    _channel.invokeMethod("reStartScan");
  }

  ///获取当前设备状态
  static Future<Status> getStatus() async {
    int result = await _channel.invokeMethod("getStatus");
    return Status.values[result];
  }

  static void addEventHandler({
    void Function(String)? dataCallback,
    EventHandler? onDiscoverPeripheral,
    EventHandlerInt? onUpdateState
  }) {
    _onDataCallback = dataCallback;
    _onDiscoverPeripheral = onDiscoverPeripheral;
    _onUpdateState = onUpdateState;
    _channel.setMethodCallHandler(_handleMethod);
  }

  static Future<dynamic> _handleMethod(MethodCall call ) async {
    switch (call.method) {
      case "onDiscoverPeripheral":
        return _onDiscoverPeripheral!(call.arguments.cast<String, dynamic>());
      case "onUpdateState": ///0-未连接；1-正在连接；2-已连接； 3-断开连接; 4-连接失败
        int state = call.arguments;
        return _onUpdateState!(Status.values[state]);
      case "dataCallback" :
        return _onDataCallback!(call.arguments);
      default:
        throw new UnsupportedError("Unrecognized Event");
    }
  }

  // /// 监听蓝牙的回调信息
  // ///
  // /// [dataCallback] 蓝牙扫码出来的结果
  // ///
  // /* [stateChange] 蓝牙连接状态变更。///0-未连接；1-正在连接；2-已连接； 3-断开连接; 4-连接失败；5-连接超时；6-蓝牙未开启; 7-蓝牙权限未开启;*/
  // static void listen(void Function(String) dataCallback/*, {void Function(int)? stateChange}*/) {
  //   _listenChannel.receiveBroadcastStream().listen((event) {
  //     String data = event;
  //     if(data.startsWith("#")) {
  //         dataCallback(data.substring(1));
  //     } else if(data.startsWith("@")) {
  //         // if(stateChange != null) {
  //         //   int v = int.parse(data.substring(1));
  //         //   stateChange(v);
  //         // }
  //     }
  //   });
  // }
}
